package cn.yuan.product.service.impl;

import cn.yuan.basic.service.impl.BaseServiceImpl;
import cn.yuan.product.domain.Product;
import cn.yuan.product.domain.ProductDetail;
import cn.yuan.product.mapper.ProductDetailMapper;
import cn.yuan.product.mapper.ProductMapper;
import cn.yuan.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService{

    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional
    public void remove(Long productId) {
        //1.通过服务Id 删除服务详情
        productDetailMapper.deleteByProductId(productId);
        productMapper.delete(productId);
    }

    @Override
    public void save(Product product) {
        productMapper.save(product);//需要返回主键
        ProductDetail detail = product.getDetail();
        if(detail != null){
            detail.setProduct_id(product.getId());
            productDetailMapper.save(detail);
        }
    }

    @Override
    public void update(Product product) {
        productMapper.update(product);
        ProductDetail detail = product.getDetail();
        if(detail != null){
            detail.setProduct_id(product.getId());
            if(detail.getId() != null){
                productDetailMapper.update(detail);
            }else{
                productDetailMapper.save(detail);
            }

        }

    }

    @Override
    public ProductDetail findDetailByProductId(Long productId) {
        return productDetailMapper.loadByProductId(productId);
    }

    /**
     * 批量上架或下架
     * @param ids
     * @param flag   0下架  1 上架
     */
    @Override
    public void onOrOffSale(List<Long> ids, int flag) {
        Map<String,Object> map = new HashMap<>();
        map.put("ids", ids);
        if(flag==1){
            map.put("onsaletimg", new Date());
            productMapper.onSale(map);
        }else {
            map.put("offsaletime", new Date());
            productMapper.offSale(map);
        }
    }
}
